package com.gcb.controller.system;

import com.gcb.common.constant.Constants;
import com.gcb.common.core.domain.AjaxResult;
import com.gcb.common.core.domain.entity.SysDept;
import com.gcb.common.core.domain.entity.SysMenu;
import com.gcb.common.core.domain.entity.SysUser;
import com.gcb.framework.model.LoginBody;
import com.gcb.framework.model.LoginUser;
import com.gcb.framework.utils.SecurityUtils;
import com.gcb.common.utils.StringUtils;
import com.gcb.framework.web.service.SysLoginService;
import com.gcb.framework.web.service.SysPermissionService;
import com.gcb.framework.web.service.TokenService;
import com.gcb.framework.domain.vo.UserDeptVo;
import com.gcb.framework.mapper.SysUserRoleMapper;
import com.gcb.framework.service.ISysDeptService;
import com.gcb.framework.service.ISysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Set;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
public class SysLoginController {
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private ISysDeptService deptService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@Validated @RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid(), loginBody.getLoginType());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //所属公司的信息
        Long operateId = SecurityUtils.getLoginUser().getOperateId();
        SysDept sysDept = deptService.selectDeptById(operateId);
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("operateId", operateId);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }

    /**
     * 切换运营部门
     *
     * @param deptId 部门id
     * @return AjaxResult
     */
    @GetMapping("toggleDept")
    public AjaxResult toggleDept(HttpServletRequest request,Long deptId) {
        Long userId = SecurityUtils.getUserId();
        if (ObjectUtils.isEmpty(userId)) {
            return AjaxResult.error("请先登录");
        }
        if (ObjectUtils.isEmpty(deptId)) {
            return AjaxResult.error("所选部门不可为空");
        }
        if (deptId.equals(SecurityUtils.getDeptId())) {
            return AjaxResult.success("当前登录部门无需切换");
        }
        try {
            String newToken = loginService.toggleDept(userId, deptId);
            //将旧token清除
            LoginUser loginUser = tokenService.getLoginUser(request);
            if (StringUtils.isNotNull(loginUser)) {
                // 删除用户缓存记录
                tokenService.delLoginUser(loginUser.getToken());
            }
            AjaxResult ajax = AjaxResult.success("切换部门成功");
            ajax.put("token", newToken);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error("切换部门异常");
        }
    }

    /**
     * 获取用户运营部门列表
     *
     * @return 运营部门列表
     */
    @GetMapping("getUserDeptList")
    public AjaxResult getUserDeptList() {
        Long userId = SecurityUtils.getUserId();
        List<UserDeptVo> deptList = sysUserRoleMapper.getUserDeptList(userId);
        return AjaxResult.success(deptList);
    }
}
